<template>
  <view class="container">
    <!-- 相机组件 -->
    <camera
      class="camera"
      mode="scanCode"
      device-position="back"
      flash="off"
      @error="onCameraError"
      @scancode="onScanCode"
    >
      <view class="scan-mask">
        <view class="scan-line" :style="{ top: lineTop + 'px' }"></view>
      </view>
      <!-- 在相机界面上添加按钮 -->
      <view class="button-container">
        <button class="btn" @click="handleCoupon">卡密核销</button>
      </view>
    </camera>
  </view>
</template>
<script>
export default {
  data() {
    return {
      lineTop: 0,
      animationInterval: null
    };
  },
  onShow() {
    console.log('来了');
    this.startScanAnimation();
  },
  // 页面周期函数--监听页面卸载
  onHide() {
    console.log('走了');
    this.stopScanAnimation();
  },
  methods: {
    startScanAnimation() {
      this.animationInterval = setInterval(() => {
        this.lineTop = (this.lineTop + 2) % 300; // 300 是扫描区域的高度
      }, 20);
    },
    stopScanAnimation() {
      if (this.animationInterval) {
        clearInterval(this.animationInterval);
        this.animationInterval = null;
      }
    },
    // 扫码功能
    onScanCode(e) {
      console.log('扫码结果:', e);
      uni.showToast({
        title: e.detail.result,
        icon: 'none'
      });
      uni.navigateTo({
        url: '/pages/scan/coupon/coupon?result=' + e.detail.result
      });
    },

    // 卡密核销功能
    handleCoupon() {
      uni.navigateTo({
        url: '/pages/scan/coupon/coupon'
      });
    },

    // 相机错误处理
    onCameraError(err) {
      console.error('相机错误:', err);
      uni.showToast({
        title: '相机初始化失败',
        icon: 'none'
      });
    }
  }
};
</script>
<style scoped>
.container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.camera {
  width: 100%;
  height: 100%;
}

.button-container {
  position: absolute;
  top: 40rpx;
  right: 20rpx;
}

.btn {
  width: 200rpx;
  background-color: #007AFF;
  color: white;
  border-radius: 20rpx;
}

.scan-mask {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 700rpx;
    height: 700rpx;
    overflow: hidden;
}

.scan-line {
    position: absolute;
    left: 0;
    width: 100%;
    height: 50rpx;
    background-image: radial-gradient(ellipse farthest-side at bottom,#26b26d, transparent);
    /* animation: scan 3s linear infinite; */
    /* box-shadow: 10px -10px 30px 10px #00ff00; 初始阴影 */
}

@keyframes scan {
  0% { top: 0; opacity: 1; }
  90% { top: 90%;opacity: 1; }
  100% { top: 100%; opacity: 0; }
}
</style>
